package ylh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import ylh.common.CustomException;
import ylh.common.R;
import ylh.dto.DishDto;
import ylh.entity.Category;
import ylh.entity.Dish;
import ylh.entity.DishFlavor;
import ylh.entity.SetmealDish;
import ylh.service.CategoryService;
import ylh.service.DishFlavorService;
import ylh.service.DishService;
import ylh.service.SetmealDishService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private DishFlavorService dishFlavorService;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private CacheManager cacheManager;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("page = {},pageSize = {}", page, pageSize);
        //构造分页构造器
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name != null, Dish::getName, name);
        //按更新时间排序
        queryWrapper.orderByAsc(Dish::getUpdateTime);

        //执行查询
        dishService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId + '_' + #dish.status")
    public R<List<DishDto>> getsById(Dish dish) {
        List<DishDto> dishDtos = null;
//        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        
        //先从Redis获取数据，
//        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        
        //如果Redis中有缓存就从Redis中获取，如果没有缓存就在mysql中查询
//        if (dishDtos != null) {
//            return R.success(dishDtos);
//        }
        
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(queryWrapper);

        dishDtos = dishList.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);
            if (!dishFlavors.isEmpty()){
                dishDto.setFlavors(dishFlavors);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将菜品数据缓存到Redis
//        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

    @PostMapping
    @CacheEvict(value = "dishCache", allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        
        //如果数据有修改，清理该菜品所在分类的Redis缓存
//        String key = "dish_" + dishDto.getCategoryId() + "_1";
//        redisTemplate.delete(key);
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        return R.success("新增菜品成功");
    }


    @CacheEvict(value = "dishCache", allEntries = true)
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {

        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(Dish::getId, ids);
        queryWrapper1.eq(Dish::getStatus, 1);

        int count = (int) dishService.count(queryWrapper1);
        if (count > 0) {
            throw new CustomException("套餐正在售卖，不能删除");
        }
        
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        count = (int) setmealDishService.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("套餐内有该菜品，无法删除");
        }
        
        
        dishService.removeByIds(ids);
        
        return R.success("删除成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        Dish dish = new Dish();
        dish.setStatus(status);
        for (Long id : ids
        ) {
            dish.setId(id);
            dishService.updateById(dish);
        }
        return R.success("成功");
    }

    @PutMapping
    public R<String> updateById(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //如果数据有修改，清理该菜品所在分类的Redis缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        /*List<DishFlavor> flavors = dishDto.getFlavors();
        LocalDateTime localDateTime = LocalDateTime.now();
        for (DishFlavor dishFlavor :
                flavors) {
            dishFlavor.setUpdateTime(localDateTime);
            if (dishFlavor.getDishId() == null){
                dishFlavor.setDishId(id);
                dishFlavorService.save(dishFlavor);
            }else {
                dishFlavorService.updateById(dishFlavor);
            } 
        }

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        for (DishFlavor dishFlavor :
                dishFlavors) {
            if (dishFlavor.getUpdateTime() != localDateTime){
                dishFlavorService.removeById(dishFlavor.getId());
            }
        }*/

        return R.success("更改成功");
    }
}
